export const formArrItem2str = (formData) => {
    for (let key in formData) {
        const item = formData[key]
        if (Array.isArray(item)) {
            formData[key] = item.join(',')
        }
    }
    return formData
}

export const checkEmail = str => {
    const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
    return reg.test(str)
}

export const checkPhone = str => {
    const regMobile = /^1[3456789]\d{9}$/
    const regPhone = /([0-9]{3,4}-)?[0-9]{7,8}/
    return regMobile.test(str) || regPhone.test(str)
}



export const validate = (type, instance, model, field) => {
    if (type === 'idCard') {
        return function (rule, value, callback) {
            if (value.length != 18) {
                return callback(new Error('请输入正确的身份证号码'))
            } else {
                return callback()
            }
        }
    }
    if (type === 'phone') {
        return function (rule, value, callback) {
            const reg = /^1[3456789]\d{9}$/
            if (!reg.test(value)) {
                return callback(new Error('请输入正确的手机号码'))
            } else {
                return callback()
            }
        }
    }
    if (type === 'email') {
        return function (rule, value, callback, model) {
            const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
            if (!reg.test(value)) {
                return callback(new Error('请输入正确的邮箱'))
            } else {
                return callback()
            }
        }
    }
    if (type === 'ip') {
        return function (rule, value, callback, ) {
            const port = instance[model][field]
            const reg = /^((https|http)?:\/\/\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            const notPort = isNaN(port) || port > 65535 || port < 1
            if (!value || !port) {
                return callback()
            }
            if (!reg.test(value) || notPort) {
                return callback(new Error('请输入正确的IP地址和端口'))
            } else {
                return callback()
            }
        }
    }
    if (type === 'port') {
        return function (rule, value, callback) {
            const port = +value
            if (isNaN(port) || port > 65535 || port < 1) {
                return (new Error('请输入正确的端口'))
            } else {
                return callback()
            }
        }
    }
}
